<template>
  <div
    style="
      margin: -20px;
      margin-right: 0;
      padding: 20px;
      height: 100%;
      display: grid;
      gap: 24px;
      box-sizing: border-box;
      grid-template-columns: 1fr 1fr 1fr 1fr;
      overflow: auto;
    "
  >
    <div class="card-content" @click="handleContent()">
      <el-card>
        <div
          style="
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            flex-direction: column;
          "
        >
          <i class="el-icon-circle-plus-outline" style="font-size: 60px; padding: 20px"></i>
          <div>新建</div>
        </div>
      </el-card>
    </div>

    <div v-for="(item, key) in list" :key="key" class="card-content">
      <el-card style="display: flex; flex-direction: column">
        <div style="height: 100%; display: flex; flex-direction: column">
          <el-image v-if="!item.url.endsWith('mp4')" :src="item.url" style="flex: 1"></el-image>
          <div v-else style="overflow: hidden">
            <video :src="item.url" style="flex: 1; width: 100%"></video>
          </div>
          <div style="font-size: 16px; margin: 12px 0 20px">
            <h4>{{ item.title }}</h4>
            <span style="font-size: 12px; color: #b0a8ba">来源于: {{ item.author }}</span>
          </div>
          <div style="display: flex; justify-content: space-between">
            <div style="font-size: 12px">
              <p>浏览量：{{ item.view }}</p>
              <br />
              <p>收藏量：{{ item.collect_user.length }}</p>
            </div>
            <div style="padding-right: 12px">
              <el-button type="text" size="medium" @click="handleContent(item, true)"
                >编辑</el-button
              >
              <el-button type="text" size="medium" @click="delContent(item)">删除</el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <el-dialog
      title="内容填写"
      :visible.sync="dialog_visible"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        :model="form"
        ref="ruleForm"
        label-width="80px"
        :rules="rules"
        style="padding-right: 40px"
      >
        <el-form-item label="渠道" prop="channel">
          <el-select v-model="form.channel">
            <el-option label="知识库" value="knowledge"></el-option>
            <el-option label="药物知识" value="drug"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="展示" prop="url">
          <Upload @upload="handleFileUpload" :imageUrl="form.url"></Upload>
        </el-form-item>
        <el-form-item label="来源" prop="author">
          <el-input v-model="form.author"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" :rows="4" v-model="form.content"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumbs from '@/components/BreadCrumbs';
import Upload from '@/comp/Upload';
import { pick } from 'lodash';

const genDefaultForm = () => ({
  id: null,
  channel: 'knowledge',
  url: '',
  title: '',
  content: '',
  author: '',
});
export default {
  data() {
    return {
      dialog_visible: false,
      form: genDefaultForm(),
      file: {},
      rules: {
        channel: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change',
          },
        ],
        title: [{ required: true, message: '请输入标题', trigger: 'change' }],
        author: [{ required: true, message: '请输入来源', trigger: 'change' }],
        content: [{ required: true, message: '请输入内容', trigger: 'change' }],
        type: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change',
          },
        ],
        url: [
          {
            message: '请选择图片',
            required: true,
            trigger: 'change',
          },
        ],
      },
      list: [],
    };
  },
  components: {
    BreadCrumbs,
    Upload,
  },
  created() {
    this.getData();
  },
  methods: {
    async getData() {
      const { msg, data, code } = await this.$http.get('/api/knowledge');
      if (code) return this.$message.error(msg);
      this.list = data;
    },
    async handleContent(item, edit = false) {
      this.form.id = null;
      if (edit) {
        const obj = pick(item, Object.keys(this.form));
        Object.assign(this.form, obj);
      } else {
        this.form = genDefaultForm();
        // 重置表单校验
        this.$refs.ruleForm?.resetFields();
      }
      this.dialog_visible = true;
    },
    async delContent(item) {
      this.deleteMessageBox({
        message: '是否确认删除该条目？',
      }).then(async () => {
        const { code, msg } = await this.$http.delete(`/api/knowledge/${item.id}`);
        if (code) return this.$message.error(msg);
        await this.getData();
        this.$message.success(msg);
      });
    },

    handleFileUpload(file) {
      const allowed_types = ['image/jpeg', 'image/png', 'video/mp4'];
      const file_size = 1024 * 1024 * 15; // 后端校验的是30m，前端允许调整到最大30m
      if (!allowed_types.includes(file.raw.type)) {
        return this.$message.error('无效的文件类型。只允许 JPEG、PNG、MP4');
      }

      if (file.size > file_size) {
        return this.$message.error(`文件大小超过限制。最大允许 ${(file_size / (1024 * 1024)).toFixed(0)}M`);
      }
      this.form.url = file.url;
      this.file = file.raw;
    },
    async onSubmit() {
      let formData = new FormData();
      formData.append('file', this.file);
      // 添加其他表单数据到 FormData 中
      for (let key in this.form) {
        formData.append(key, this.form[key]);
      }

      try {
        await this.$refs.ruleForm?.validate();

        const { code, msg } = await this.$http.post('/api/knowledge', formData);
        if (code) return this.$message.error(msg);
        this.dialog_visible = false;
        this.$message.success('添加成功');
        await this.getData();
      } catch (error) {
        this.$message.error('请正确填写信息');
      }
    },
  },
};
</script>

<style scoped lang="less">
.card-content {
  cursor: pointer;
  height: 100%;
  height: 250px;
}
::v-deep {
  .el-card__body {
    height: 100%;
    box-sizing: border-box;
  }
  .el-card {
    height: 100%;
    box-sizing: border-box;
  }
  .el-dialog {
    margin-top: 4vh !important;
  }
}
img {
  width: 100%;
  max-height: 200px;
}
</style>
